/*!
 * c18_boolean_logic - 布尔逻辑：与或非运算
 * 
 * 《Rust基础数据类型实战Cookbook》系列第18个案例
 * 全面掌握 Rust 中的布尔逻辑运算，深入理解与或非操作的原理和应用
 * 
 * 本案例涵盖：
 * - 逻辑与运算(&&)：同时满足多个条件
 * - 逻辑或运算(||)：满足任一条件即可
 * - 逻辑非运算(!)：条件取反操作
 * - 运算符优先级和结合性
 * - 短路求值机制的深入理解
 * - 复杂逻辑表达式的构建和优化
 * - 德摩根定律的实际应用
 * - 真值表分析和逻辑推理
 * - 条件判断的高级技巧和最佳实践
 */

fn main() {
    println!("=== Rust 布尔逻辑运算详解 ===\n");
    
    // 1. 布尔逻辑概述
    demonstrate_logic_overview();
    println!();
    
    // 2. 逻辑与运算(&& 操作符)
    demonstrate_logical_and();
    println!();
    
    // 3. 逻辑或运算(|| 操作符)
    demonstrate_logical_or();
    println!();
    
    // 4. 逻辑非运算(! 操作符)
    demonstrate_logical_not();
    println!();
    
    // 5. 运算符优先级和结合性
    demonstrate_operator_precedence();
    println!();
    
    // 6. 短路求值机制
    demonstrate_short_circuit_evaluation();
    println!();
    
    // 7. 复杂逻辑表达式
    demonstrate_complex_expressions();
    println!();
    
    // 8. 德摩根定律
    demonstrate_de_morgan_laws();
    println!();
    
    // 9. 真值表分析
    demonstrate_truth_tables();
    println!();
    
    // 10. 实际应用场景
    demonstrate_practical_applications();
    println!();
    
    println!("=== 布尔逻辑运算学习完成！===");
}

/// 1. 演示布尔逻辑的基础概念
fn demonstrate_logic_overview() {
    println!("1. 布尔逻辑概述");
    println!("   布尔逻辑是基于布尔代数的逻辑系统，处理 true 和 false 之间的关系");
    println!("   Rust 提供三个基本的布尔逻辑运算符：&&（与）、||（或）、!（非）");
    println!();
    
    println!("1.1 逻辑运算符概览");
    println!("   &&  - 逻辑与（AND）：所有条件都必须为 true，结果才为 true");
    println!("   ||  - 逻辑或（OR）：任意一个条件为 true，结果就为 true");
    println!("   !   - 逻辑非（NOT）：将 true 变为 false，false 变为 true");
    println!();
    
    println!("1.2 基本示例");
    let a = true;
    let b = false;
    
    println!("   设 a = {}, b = {}", a, b);
    println!("   a && b = {} (逻辑与：两个都为 true 才为 true)", a && b);
    println!("   a || b = {} (逻辑或：至少一个为 true 就为 true)", a || b);
    println!("   !a = {} (逻辑非：true 变为 false)", !a);
    println!("   !b = {} (逻辑非：false 变为 true)", !b);
    println!();
    
    println!("1.3 为什么需要布尔逻辑？");
    println!("   • 复杂条件判断：多个条件的组合评估");
    println!("   • 权限检查：多重权限验证");
    println!("   • 状态控制：多状态的逻辑判断");
    println!("   • 搜索过滤：多条件筛选");
    println!("   • 业务规则：复杂业务逻辑实现");
}

/// 2. 演示逻辑与运算(&&)
fn demonstrate_logical_and() {
    println!("2. 逻辑与运算(&&)");
    println!("   逻辑与要求所有操作数都为 true，结果才为 true");
    println!("   任何一个操作数为 false，整个表达式就为 false");
    println!();
    
    println!("2.1 基本逻辑与运算");
    let results = [
        (true, true, true && true),
        (true, false, true && false),
        (false, true, false && true),
        (false, false, false && false),
    ];
    
    for (a, b, result) in results {
        println!("   {} && {} = {}", a, b, result);
    }
    println!();
    
    println!("2.2 多个操作数的与运算");
    let cond1 = true;
    let cond2 = true;
    let cond3 = false;
    let cond4 = true;
    
    println!("   设条件：cond1={}, cond2={}, cond3={}, cond4={}", cond1, cond2, cond3, cond4);
    println!("   cond1 && cond2 = {}", cond1 && cond2);
    println!("   cond1 && cond2 && cond3 = {}", cond1 && cond2 && cond3);
    println!("   cond1 && cond2 && cond4 = {}", cond1 && cond2 && cond4);
    println!("   所有条件 = {}", cond1 && cond2 && cond3 && cond4);
    println!();
    
    println!("2.3 实际应用示例：权限验证");
    let user_logged_in = true;
    let user_is_admin = true;
    let feature_enabled = true;
    let has_permission = false;
    
    let can_access = user_logged_in && user_is_admin && feature_enabled && has_permission;
    
    println!("   用户登录: {}", user_logged_in);
    println!("   管理员权限: {}", user_is_admin);
    println!("   功能开启: {}", feature_enabled);
    println!("   特殊权限: {}", has_permission);
    println!("   最终访问权限: {}", can_access);
    println!();
    
    println!("2.4 条件表达式中的应用");
    let age = 25;
    let has_license = true;
    let has_car = true;
    let weather_good = false;
    
    if age >= 18 && has_license && has_car && weather_good {
        println!("   可以开车出行");
    } else {
        println!("   不建议开车出行");
        // 详细分析每个条件
        if age < 18 {
            println!("     - 年龄不足18岁");
        }
        if !has_license {
            println!("     - 没有驾驶证");
        }
        if !has_car {
            println!("     - 没有车辆");
        }
        if !weather_good {
            println!("     - 天气不好");
        }
    }
}

/// 3. 演示逻辑或运算(||)
fn demonstrate_logical_or() {
    println!("3. 逻辑或运算(||)");
    println!("   逻辑或只要有一个操作数为 true，结果就为 true");
    println!("   只有当所有操作数都为 false 时，结果才为 false");
    println!();
    
    println!("3.1 基本逻辑或运算");
    let results = [
        (true, true, true || true),
        (true, false, true || false),
        (false, true, false || true),
        (false, false, false || false),
    ];
    
    for (a, b, result) in results {
        println!("   {} || {} = {}", a, b, result);
    }
    println!();
    
    println!("3.2 多个操作数的或运算");
    let option1 = false;
    let option2 = false;
    let option3 = true;
    let option4 = false;
    
    println!("   设选项：option1={}, option2={}, option3={}, option4={}", option1, option2, option3, option4);
    println!("   option1 || option2 = {}", option1 || option2);
    println!("   option1 || option2 || option3 = {}", option1 || option2 || option3);
    println!("   option1 || option2 || option4 = {}", option1 || option2 || option4);
    println!("   任意选项可用 = {}", option1 || option2 || option3 || option4);
    println!();
    
    println!("3.3 实际应用示例：登录方式验证");
    let password_correct = false;
    let fingerprint_valid = false;
    let face_id_valid = true;
    let sms_code_valid = false;
    
    let login_successful = password_correct || fingerprint_valid || face_id_valid || sms_code_valid;
    
    println!("   密码正确: {}", password_correct);
    println!("   指纹验证: {}", fingerprint_valid);
    println!("   面部识别: {}", face_id_valid);
    println!("   短信验证: {}", sms_code_valid);
    println!("   登录成功: {}", login_successful);
    
    if login_successful {
        println!("   ✓ 至少一种认证方式通过，允许登录");
    } else {
        println!("   ✗ 所有认证方式都失败，拒绝登录");
    }
    println!();
    
    println!("3.4 紧急情况处理");
    let fire_alarm = false;
    let security_breach = false;
    let power_failure = false;
    let medical_emergency = true;
    
    let emergency_protocol = fire_alarm || security_breach || power_failure || medical_emergency;
    
    println!("   火灾报警: {}", fire_alarm);
    println!("   安全威胁: {}", security_breach);
    println!("   电力故障: {}", power_failure);
    println!("   医疗急救: {}", medical_emergency);
    
    if emergency_protocol {
        println!("   🚨 触发应急预案！");
        // 确定具体的紧急情况
        if fire_alarm {
            println!("     启动消防程序");
        }
        if security_breach {
            println!("     启动安全协议");
        }
        if power_failure {
            println!("     启动备用电源");
        }
        if medical_emergency {
            println!("     联系医疗服务");
        }
    } else {
        println!("   ✓ 系统运行正常");
    }
}

/// 4. 演示逻辑非运算(!)
fn demonstrate_logical_not() {
    println!("4. 逻辑非运算(!)");
    println!("   逻辑非是一元运算符，将 true 变为 false，false 变为 true");
    println!("   用于条件取反、状态切换和逻辑否定");
    println!();
    
    println!("4.1 基本逻辑非运算");
    let true_val = true;
    let false_val = false;
    
    println!("   !{} = {}", true_val, !true_val);
    println!("   !{} = {}", false_val, !false_val);
    println!();
    
    println!("4.2 双重否定");
    let original = true;
    let single_negation = !original;
    let double_negation = !!original;
    
    println!("   原值: {}", original);
    println!("   一次取反: {}", single_negation);
    println!("   双重取反: {}", double_negation);
    println!("   双重取反规律：!!x = x");
    println!();
    
    println!("4.3 条件取反的实际应用");
    let user_banned = false;
    let system_maintenance = false;
    let service_available = true;
    
    // 服务可用的条件：用户未被禁止 且 系统未维护 且 服务本身可用
    let can_use_service = !user_banned && !system_maintenance && service_available;
    
    println!("   用户被禁: {}", user_banned);
    println!("   系统维护: {}", system_maintenance);
    println!("   服务可用: {}", service_available);
    println!("   用户未被禁: {}", !user_banned);
    println!("   系统未维护: {}", !system_maintenance);
    println!("   最终可用: {}", can_use_service);
    println!();
    
    println!("4.4 状态切换示例");
    let mut is_playing = false;
    let mut is_paused = true;
    let mut is_muted = false;
    
    println!("   初始状态:");
    println!("     播放中: {}", is_playing);
    println!("     暂停中: {}", is_paused);
    println!("     静音: {}", is_muted);
    
    // 切换播放状态
    is_playing = !is_playing;
    is_paused = !is_paused;
    
    println!("   点击播放按钮后:");
    println!("     播放中: {}", is_playing);
    println!("     暂停中: {}", is_paused);
    println!("     静音: {}", is_muted);
    
    // 切换静音状态
    is_muted = !is_muted;
    
    println!("   点击静音按钮后:");
    println!("     播放中: {}", is_playing);
    println!("     暂停中: {}", is_paused);
    println!("     静音: {}", is_muted);
    println!();
    
    println!("4.5 否定条件的优雅处理");
    let items = vec![1, 2, 3, 4, 5];
    let min_length = 3;
    let max_length = 10;
    
    let not_empty = !items.is_empty();
    let not_too_short = !(items.len() < min_length);
    let not_too_long = !(items.len() > max_length);
    let valid_collection = not_empty && not_too_short && not_too_long;
    
    println!("   集合: {:?}", items);
    println!("   不为空: {}", not_empty);
    println!("   不太短: {}", not_too_short);
    println!("   不太长: {}", not_too_long);
    println!("   有效集合: {}", valid_collection);
}

/// 5. 演示运算符优先级和结合性
fn demonstrate_operator_precedence() {
    println!("5. 运算符优先级和结合性");
    println!("   理解逻辑运算符的优先级对于正确构造复杂表达式至关重要");
    println!("   优先级：! > && > ||");
    println!();
    
    println!("5.1 优先级规则");
    println!("   1. !（非）- 最高优先级，一元运算符");
    println!("   2. &&（与）- 中等优先级");
    println!("   3. ||（或）- 最低优先级");
    println!("   4. 同级运算符从左到右结合");
    println!();
    
    println!("5.2 无括号表达式的求值");
    let a = true;
    let b = false;
    let c = true;
    let d = false;
    
    println!("   设：a={}, b={}, c={}, d={}", a, b, c, d);
    println!();
    
    // 演示不同的优先级组合
    let expr1 = !a && b || c;
    let explicit1 = ((!a) && b) || c;
    println!("   !a && b || c = {}", expr1);
    println!("   等价于: ((!a) && b) || c = {}", explicit1);
    println!();
    
    let expr2 = a && !b || c && d;
    let explicit2 = (a && (!b)) || (c && d);
    println!("   a && !b || c && d = {}", expr2);
    println!("   等价于: (a && !b) || (c && d) = {}", explicit2);
    println!();
    
    let expr3 = !a || b && !c;
    let explicit3 = (!a) || (b && (!c));
    println!("   !a || b && !c = {}", expr3);
    println!("   等价于: (!a) || (b && (!c)) = {}", explicit3);
    println!();
    
    println!("5.3 括号改变优先级");
    let expr4 = (a || b) && (c || d);
    let no_brackets = a || b && c || d;
    
    println!("   (a || b) && (c || d) = {}", expr4);
    println!("   a || b && c || d = {}", no_brackets);
    println!("   注意：括号改变了运算顺序！");
    println!();
    
    println!("5.4 复杂表达式分解");
    let user_active = true;
    let account_verified = false;
    let payment_valid = true;
    let terms_accepted = true;
    let age_verified = false;
    
    // 复杂的业务逻辑
    let can_purchase = user_active && (account_verified || payment_valid) && 
                      terms_accepted && !age_verified;
    
    println!("   用户激活: {}", user_active);
    println!("   账户验证: {}", account_verified);
    println!("   付款有效: {}", payment_valid);
    println!("   同意条款: {}", terms_accepted);
    println!("   年龄验证: {}", age_verified);
    println!();
    
    // 分步计算
    let verification_ok = account_verified || payment_valid;
    let not_age_restricted = !age_verified;
    let final_result = user_active && verification_ok && terms_accepted && not_age_restricted;
    
    println!("   验证通过: {} (账户验证 || 付款有效)", verification_ok);
    println!("   无年龄限制: {} (!年龄验证)", not_age_restricted);
    println!("   最终结果: {}", final_result);
    println!("   可以购买: {}", can_purchase);
}

/// 6. 演示短路求值机制
fn demonstrate_short_circuit_evaluation() {
    println!("6. 短路求值机制");
    println!("   Rust 的逻辑运算符支持短路求值，可以提高性能并避免不必要的计算");
    println!("   &&：左侧为 false 时，右侧不会被计算");
    println!("   ||：左侧为 true 时，右侧不会被计算");
    println!();
    
    println!("6.1 && 运算符的短路求值");
    
    // 模拟一个可能出错的函数
    fn expensive_check(name: &str) -> bool {
        println!("     执行昂贵的检查: {}", name);
        true
    }
    
    let condition1 = false;
    let condition2 = true;
    
    println!("   测试 1: condition1={} && expensive_check()", condition1);
    let result1 = condition1 && expensive_check("检查A");
    println!("   结果: {}", result1);
    println!("   注意：expensive_check 没有被调用！");
    println!();
    
    println!("   测试 2: condition2={} && expensive_check()", condition2);
    let result2 = condition2 && expensive_check("检查B");
    println!("   结果: {}", result2);
    println!("   注意：expensive_check 被调用了！");
    println!();
    
    println!("6.2 || 运算符的短路求值");
    
    let condition3 = true;
    let condition4 = false;
    
    println!("   测试 3: condition3={} || expensive_check()", condition3);
    let result3 = condition3 || expensive_check("检查C");
    println!("   结果: {}", result3);
    println!("   注意：expensive_check 没有被调用！");
    println!();
    
    println!("   测试 4: condition4={} || expensive_check()", condition4);
    let result4 = condition4 || expensive_check("检查D");
    println!("   结果: {}", result4);
    println!("   注意：expensive_check 被调用了！");
    println!();
    
    println!("6.3 短路求值的实际应用");
    
    // 安全的数组访问
    fn safe_array_access() {
        let numbers = vec![1, 2, 3];
        let index = 5;
        
        println!("   数组: {:?}, 索引: {}", numbers, index);
        
        // 先检查索引范围，再访问元素（避免 panic）
        if index < numbers.len() && numbers[index] > 0 {
            println!("   元素大于 0");
        } else {
            println!("   索引越界或元素不大于 0");
        }
        
        // 如果没有短路求值，这里会 panic
        println!("   短路求值避免了数组越界访问");
    }
    
    safe_array_access();
    println!();
    
    println!("6.4 利用短路求值优化性能");
    
    // 模拟不同开销的检查函数
    fn quick_check() -> bool {
        println!("     执行快速检查（低成本）");
        false
    }
    
    fn moderate_check() -> bool {
        println!("     执行中等检查（中等成本）");
        std::thread::sleep(std::time::Duration::from_millis(1));
        true
    }
    
    fn expensive_operation() -> bool {
        println!("     执行昂贵操作（高成本）");
        std::thread::sleep(std::time::Duration::from_millis(5));
        true
    }
    
    println!("   优化策略：将最可能失败且成本最低的条件放在前面");
    let optimized_result = quick_check() && moderate_check() && expensive_operation();
    println!("   优化后的结果: {}", optimized_result);
    println!("   由于 quick_check() 返回 false，后续操作被跳过");
    println!();
    
    println!("6.5 短路求值与副作用");
    let mut counter = 0;
    
    fn increment_counter(counter: &mut i32, name: &str) -> bool {
        *counter += 1;
        println!("     {}：计数器 = {}", name, counter);
        true
    }
    
    println!("   演示副作用在短路求值中的行为:");
    let condition = false;
    println!("   condition={} && increment_counter()", condition);
    let _ = condition && increment_counter(&mut counter, "副作用函数");
    println!("   最终计数器值: {}", counter);
    println!("   说明：由于短路求值，副作用函数未被执行");
}

/// 7. 演示复杂逻辑表达式
fn demonstrate_complex_expressions() {
    println!("7. 复杂逻辑表达式");
    println!("   学习如何构建、理解和优化复杂的多层逻辑表达式");
    println!();
    
    println!("7.1 多层嵌套表达式");
    
    // 模拟电商系统的复杂权限检查
    let user_age = 25;
    let is_vip = true;
    let account_balance = 150.0;
    let product_price = 120.0;
    let is_weekend = false;
    let has_coupon = true;
    let stock_available = true;
    let shipping_available = true;
    
    println!("   电商购买条件检查:");
    println!("     用户年龄: {}", user_age);
    println!("     VIP会员: {}", is_vip);
    println!("     账户余额: {}", account_balance);
    println!("     商品价格: {}", product_price);
    println!("     周末: {}", is_weekend);
    println!("     有优惠券: {}", has_coupon);
    println!("     库存可用: {}", stock_available);
    println!("     配送可用: {}", shipping_available);
    println!();
    
    // 分解复杂条件
    let age_eligible = user_age >= 18;
    let payment_ok = account_balance >= product_price || (is_vip && account_balance >= product_price * 0.8);
    let discount_applicable = (is_weekend && is_vip) || has_coupon;
    let fulfillment_possible = stock_available && shipping_available;
    
    let can_purchase = age_eligible && payment_ok && fulfillment_possible;
    let final_price = if discount_applicable { product_price * 0.9 } else { product_price };
    
    println!("   条件分析:");
    println!("     年龄符合: {}", age_eligible);
    println!("     支付能力: {}", payment_ok);
    println!("     可享折扣: {}", discount_applicable);
    println!("     可履约: {}", fulfillment_possible);
    println!("     可以购买: {}", can_purchase);
    println!("     最终价格: {:.2}", final_price);
    println!();
    
    println!("7.2 复合条件的重构");
    
    // 原始复杂表达式
    let complex_original = (user_age >= 18 && account_balance >= 100.0) && 
                          ((is_vip && !is_weekend) || (has_coupon && stock_available)) && 
                          (shipping_available || (is_vip && account_balance >= 200.0));
    
    // 重构后的清晰表达式
    let basic_eligibility = user_age >= 18 && account_balance >= 100.0;
    let special_offer = (is_vip && !is_weekend) || (has_coupon && stock_available);
    let delivery_options = shipping_available || (is_vip && account_balance >= 200.0);
    let complex_refactored = basic_eligibility && special_offer && delivery_options;
    
    println!("   复杂表达式重构:");
    println!("     基本资格: {}", basic_eligibility);
    println!("     特殊优惠: {}", special_offer);
    println!("     配送选项: {}", delivery_options);
    println!("     原始结果: {}", complex_original);
    println!("     重构结果: {}", complex_refactored);
    println!("     结果一致: {}", complex_original == complex_refactored);
    println!();
    
    println!("7.3 条件链式处理");
    
    // 用户权限等级检查
    #[derive(Debug)]
    enum UserRole {
        Guest,
        User,
        Moderator,
        Admin,
        SuperAdmin,
    }
    
    let user_role = UserRole::Moderator;
    let is_business_hours = true;
    let system_healthy = true;
    let maintenance_mode = false;
    
    let can_read = matches!(user_role, UserRole::User | UserRole::Moderator | UserRole::Admin | UserRole::SuperAdmin);
    let can_write = matches!(user_role, UserRole::Moderator | UserRole::Admin | UserRole::SuperAdmin) 
                    && is_business_hours;
    let can_delete = matches!(user_role, UserRole::Admin | UserRole::SuperAdmin) 
                     && is_business_hours && !maintenance_mode;
    let can_admin = matches!(user_role, UserRole::SuperAdmin) 
                    && system_healthy && !maintenance_mode;
    
    println!("   权限链式检查:");
    println!("     用户角色: {:?}", user_role);
    println!("     工作时间: {}", is_business_hours);
    println!("     系统健康: {}", system_healthy);
    println!("     维护模式: {}", maintenance_mode);
    println!("     可以读取: {}", can_read);
    println!("     可以写入: {}", can_write);
    println!("     可以删除: {}", can_delete);
    println!("     可以管理: {}", can_admin);
}

/// 8. 演示德摩根定律
fn demonstrate_de_morgan_laws() {
    println!("8. 德摩根定律");
    println!("   德摩根定律描述了逻辑运算符之间的等价关系");
    println!("   !(A && B) ≡ (!A) || (!B)");
    println!("   !(A || B) ≡ (!A) && (!B)");
    println!();
    
    println!("8.1 第一定律：!(A && B) ≡ (!A) || (!B)");
    let test_cases = [(true, true), (true, false), (false, true), (false, false)];
    
    for (a, b) in test_cases {
        let left_side = !(a && b);
        let right_side = !a || !b;
        let equivalent = left_side == right_side;
        
        println!("   A={}, B={}: !(A && B)={}, (!A) || (!B)={}, 等价: {}", 
                 a, b, left_side, right_side, equivalent);
    }
    println!();
    
    println!("8.2 第二定律：!(A || B) ≡ (!A) && (!B)");
    for (a, b) in test_cases {
        let left_side = !(a || b);
        let right_side = !a && !b;
        let equivalent = left_side == right_side;
        
        println!("   A={}, B={}: !(A || B)={}, (!A) && (!B)={}, 等价: {}", 
                 a, b, left_side, right_side, equivalent);
    }
    println!();
    
    println!("8.3 实际应用：条件简化");
    let user_online = true;
    let user_verified = false;
    
    // 原始复杂条件：用户不在线或未验证
    let original_condition = !(user_online && user_verified);
    
    // 使用德摩根定律简化
    let simplified_condition = !user_online || !user_verified;
    
    println!("   用户在线: {}", user_online);
    println!("   用户验证: {}", user_verified);
    println!("   原始条件 !(在线 && 验证): {}", original_condition);
    println!("   简化条件 (!在线) || (!验证): {}", simplified_condition);
    println!("   条件等价: {}", original_condition == simplified_condition);
    println!();
    
    println!("8.4 复杂表达式的德摩根变换");
    let has_permission = true;
    let within_time_limit = false;
    let quota_available = true;
    
    // 复杂的否定条件
    let complex_negation = !(has_permission && within_time_limit && quota_available);
    
    // 德摩根定律变换
    let morgan_transform = !has_permission || !within_time_limit || !quota_available;
    
    println!("   有权限: {}", has_permission);
    println!("   时间内: {}", within_time_limit);
    println!("   有配额: {}", quota_available);
    println!("   复杂否定: {}", complex_negation);
    println!("   德摩根变换: {}", morgan_transform);
    println!("   变换正确: {}", complex_negation == morgan_transform);
    
    // 解释变换的含义
    if morgan_transform {
        println!("   拒绝原因分析:");
        if !has_permission {
            println!("     - 权限不足");
        }
        if !within_time_limit {
            println!("     - 超时");
        }
        if !quota_available {
            println!("     - 配额不足");
        }
    }
}

/// 9. 演示真值表分析
fn demonstrate_truth_tables() {
    println!("9. 真值表分析");
    println!("   通过真值表系统地分析所有可能的逻辑组合");
    println!();
    
    println!("9.1 基本运算符真值表");
    println!("   A     | B     | A && B | A || B | !A");
    println!("   ------|-------|--------|--------|----");
    
    let values = [true, false];
    for a in values {
        for b in values {
            println!("   {:5} | {:5} | {:6} | {:6} | {:2}", 
                     a, b, a && b, a || b, !a);
        }
    }
    println!();
    
    println!("9.2 复杂表达式真值表");
    println!("   表达式：(A && B) || (!A && C)");
    println!("   A     | B     | C     | A && B | !A    | !A && C | 结果");
    println!("   ------|-------|-------|--------|-------|---------|-----");
    
    for a in [true, false] {
        for b in [true, false] {
            for c in [true, false] {
                let expr1 = a && b;
                let not_a = !a;
                let expr2 = not_a && c;
                let result = expr1 || expr2;
                
                println!("   {:5} | {:5} | {:5} | {:6} | {:5} | {:7} | {:4}", 
                         a, b, c, expr1, not_a, expr2, result);
            }
        }
    }
    println!();
    
    println!("9.3 逻辑等价性验证");
    println!("   验证：A || (B && C) ≡ (A || B) && (A || C)");
    println!("   A     | B     | C     | A||(B&&C) | (A||B)&&(A||C) | 等价");
    println!("   ------|-------|-------|---------|--------------|----- ");
    
    for a in [true, false] {
        for b in [true, false] {
            for c in [true, false] {
                let left_expr = a || (b && c);
                let right_expr = (a || b) && (a || c);
                let equivalent = left_expr == right_expr;
                
                println!("   {:5} | {:5} | {:5} | {:8} | {:13} | {:4}", 
                         a, b, c, left_expr, right_expr, equivalent);
            }
        }
    }
    println!();
    
    println!("9.4 实际场景的真值表应用");
    println!("   场景：用户访问权限判断");
    println!("   条件：(已登录 && 有权限) || (访客模式 && 公开内容)");
    println!();
    
    #[derive(Debug)]
    struct AccessScenario {
        logged_in: bool,
        has_permission: bool,
        guest_mode: bool,
        public_content: bool,
    }
    
    let scenarios = [
        AccessScenario { logged_in: true, has_permission: true, guest_mode: false, public_content: false },
        AccessScenario { logged_in: true, has_permission: false, guest_mode: false, public_content: true },
        AccessScenario { logged_in: false, has_permission: false, guest_mode: true, public_content: true },
        AccessScenario { logged_in: false, has_permission: false, guest_mode: false, public_content: false },
    ];
    
    println!("   登录 | 权限 | 访客 | 公开 | 用户访问 | 访客访问 | 最终结果");
    println!("   -----|------|------|------|----------|----------|----------");
    
    for scenario in scenarios {
        let user_access = scenario.logged_in && scenario.has_permission;
        let guest_access = scenario.guest_mode && scenario.public_content;
        let final_access = user_access || guest_access;
        
        println!("   {:4} | {:4} | {:4} | {:4} | {:8} | {:8} | {:8}", 
                 scenario.logged_in, scenario.has_permission, scenario.guest_mode, 
                 scenario.public_content, user_access, guest_access, final_access);
    }
}

/// 10. 演示实际应用场景
fn demonstrate_practical_applications() {
    println!("10. 实际应用场景");
    println!("    布尔逻辑在实际软件开发中的综合应用和最佳实践");
    println!();
    
    println!("10.1 智能家居控制系统");
    
    #[derive(Debug)]
    struct SmartHome {
        temperature: i32,
        humidity: i32,
        occupancy_detected: bool,
        time_hour: u8,
        energy_save_mode: bool,
        manual_override: bool,
    }
    
    let home_state = SmartHome {
        temperature: 26,
        humidity: 60,
        occupancy_detected: true,
        time_hour: 14,
        energy_save_mode: false,
        manual_override: false,
    };
    
    // 空调控制逻辑
    let too_hot = home_state.temperature > 25;
    let too_humid = home_state.humidity > 70;
    let daytime = home_state.time_hour >= 6 && home_state.time_hour <= 22;
    let occupied_and_daytime = home_state.occupancy_detected && daytime;
    let comfort_needed = too_hot || too_humid;
    
    let should_run_ac = (occupied_and_daytime && comfort_needed) || 
                        home_state.manual_override && 
                        !home_state.energy_save_mode;
    
    println!("   智能家居状态: {:?}", home_state);
    println!("   温度过高: {}", too_hot);
    println!("   湿度过高: {}", too_humid);
    println!("   白天有人: {}", occupied_and_daytime);
    println!("   需要制冷: {}", comfort_needed);
    println!("   启动空调: {}", should_run_ac);
    println!();
    
    println!("10.2 网站内容访问控制");
    
    #[derive(Debug, PartialEq)]
    enum UserType {
        Anonymous,
        Registered,
        Premium,
        Admin,
    }
    
    #[derive(Debug)]
    struct ContentAccess {
        user_type: UserType,
        content_is_free: bool,
        user_subscribed: bool,
        content_age_restricted: bool,
        user_age_verified: bool,
        geo_restricted: bool,
        user_in_allowed_region: bool,
    }
    
    let access_check = ContentAccess {
        user_type: UserType::Premium,
        content_is_free: false,
        user_subscribed: true,
        content_age_restricted: true,
        user_age_verified: true,
        geo_restricted: true,
        user_in_allowed_region: false,
    };
    
    // 复杂的访问控制逻辑
    let is_admin = access_check.user_type == UserType::Admin;
    let basic_access = access_check.user_type != UserType::Anonymous;
    let payment_access = access_check.content_is_free || 
                        (access_check.user_subscribed && 
                         matches!(access_check.user_type, UserType::Premium | UserType::Admin));
    let age_access = !access_check.content_age_restricted || access_check.user_age_verified;
    let geo_access = !access_check.geo_restricted || access_check.user_in_allowed_region;
    
    let final_access = is_admin || (basic_access && payment_access && age_access && geo_access);
    
    println!("   内容访问检查: {:?}", access_check);
    println!("   管理员权限: {}", is_admin);
    println!("   基础访问: {}", basic_access);
    println!("   付费访问: {}", payment_access);
    println!("   年龄访问: {}", age_access);
    println!("   地域访问: {}", geo_access);
    println!("   最终访问: {}", final_access);
    
    if !final_access {
        println!("   访问被拒绝，原因:");
        if !basic_access {
            println!("     - 需要用户登录");
        }
        if !payment_access {
            println!("     - 需要付费订阅");
        }
        if !age_access {
            println!("     - 需要年龄验证");
        }
        if !geo_access {
            println!("     - 地区限制");
        }
    }
    println!();
    
    println!("10.3 系统健康监控");
    
    #[derive(Debug)]
    struct SystemHealth {
        cpu_usage: f64,
        memory_usage: f64,
        disk_usage: f64,
        network_latency: u32,
        error_rate: f64,
        active_connections: u32,
    }
    
    let system = SystemHealth {
        cpu_usage: 85.5,
        memory_usage: 78.2,
        disk_usage: 92.1,
        network_latency: 150,
        error_rate: 2.5,
        active_connections: 1500,
    };
    
    // 系统状态评估
    let cpu_healthy = system.cpu_usage < 80.0;
    let memory_healthy = system.memory_usage < 85.0;
    let disk_healthy = system.disk_usage < 90.0;
    let network_healthy = system.network_latency < 100;
    let error_healthy = system.error_rate < 1.0;
    let connection_healthy = system.active_connections < 2000;
    
    // 告警级别判断
    let critical_alert = !cpu_healthy || !memory_healthy || !disk_healthy;
    let warning_alert = !network_healthy || !error_healthy || !connection_healthy;
    let system_stable = cpu_healthy && memory_healthy && disk_healthy && 
                       network_healthy && error_healthy && connection_healthy;
    
    println!("   系统监控数据: {:?}", system);
    println!("   CPU 健康: {}", cpu_healthy);
    println!("   内存健康: {}", memory_healthy);
    println!("   磁盘健康: {}", disk_healthy);
    println!("   网络健康: {}", network_healthy);
    println!("   错误率健康: {}", error_healthy);
    println!("   连接健康: {}", connection_healthy);
    println!();
    
    if critical_alert {
        println!("   🔴 系统严重告警！需要立即处理");
    } else if warning_alert {
        println!("   🟡 系统警告，建议关注");
    } else if system_stable {
        println!("   🟢 系统运行正常");
    }
    println!();
    
    println!("10.4 电商订单处理逻辑");
    
    #[derive(Debug)]
    struct Order {
        items_available: bool,
        payment_verified: bool,
        shipping_address_valid: bool,
        customer_verified: bool,
        fraud_check_passed: bool,
        inventory_sufficient: bool,
        business_hours: bool,
        special_handling_required: bool,
    }
    
    let order = Order {
        items_available: true,
        payment_verified: true,
        shipping_address_valid: true,
        customer_verified: true,
        fraud_check_passed: false,
        inventory_sufficient: true,
        business_hours: false,
        special_handling_required: true,
    };
    
    // 订单处理决策树
    let basic_requirements = order.items_available && order.inventory_sufficient;
    let payment_ok = order.payment_verified && order.fraud_check_passed;
    let shipping_ok = order.shipping_address_valid;
    let customer_ok = order.customer_verified;
    let timing_ok = order.business_hours || !order.special_handling_required;
    
    let can_process_immediately = basic_requirements && payment_ok && shipping_ok && 
                                 customer_ok && timing_ok;
    let needs_manual_review = basic_requirements && customer_ok && shipping_ok && 
                             ((!payment_ok) || (!timing_ok && order.special_handling_required));
    let should_reject = !basic_requirements || !customer_ok || !shipping_ok;
    
    println!("   订单信息: {:?}", order);
    println!("   基本要求: {}", basic_requirements);
    println!("   支付验证: {}", payment_ok);
    println!("   配送验证: {}", shipping_ok);
    println!("   客户验证: {}", customer_ok);
    println!("   时间合适: {}", timing_ok);
    println!();
    
    if can_process_immediately {
        println!("   ✅ 订单可以立即处理");
    } else if needs_manual_review {
        println!("   ⏳ 订单需要人工审核");
        if !payment_ok {
            println!("     - 支付或风控问题");
        }
        if !timing_ok {
            println!("     - 非工作时间的特殊订单");
        }
    } else if should_reject {
        println!("   ❌ 订单应该被拒绝");
        if !basic_requirements {
            println!("     - 商品或库存问题");
        }
        if !customer_ok {
            println!("     - 客户验证失败");
        }
        if !shipping_ok {
            println!("     - 配送地址无效");
        }
    }
}
